#include "uart.c"

void timer0_init()
{
    // TIMER1  TIMER0
    // 0000     0000
    // 清除低4位
    // xxxx ????  => xxxx 0000   xxxx ???? & 1111 0000
    // 通过TMOD设置Timer的工作模式
    TMOD &= 0xF0;
    // xxxx xxx1  模式1
    TMOD |= 0x01;
    // 计时器启动，发令枪
    TR0 = 1;
    // 中断使能
    ET0 = 0;
    // 中断总开关
    EA = 1;
    // 为了和uart中断共存，启用一个中断优先级
    PT0 = 1;
}

unsigned int count = 0;
// 中断 ISR
// interrupt service routine
void timer0_ISR() interrupt 1
{
    if (count < 10)
    {
        count++;
    }
    else
    {
        printf("timer0 interrupt!\n");
        count = 0;
    }
}

sbit BTN_RAND = P2 ^ 1;
sbit BTN_SEED = P2 ^ 2;
sbit BTN_TH_TL = P2 ^ 3;
unsigned int timer_seed = 0x1234;

unsigned int timer_rand()
{
    timer_seed = (timer_seed * 12345 + 67890) % 65535;
    return timer_seed;
}

unsigned int get_timer0_value()
{
    unsigned char high, low;
    do
    {
        // 确保 high和low的取值在一个中断周期内
        high = TH0;
        low = TL0;
    } while (high != TH0);
    // high 左移进行数据类型提升，组装成一个int
    return (high << 8) | low;
}

unsigned int update_timer_seed()
{
    timer_seed = get_timer0_value();
    return timer_seed;
}

void main()
{
    uart_init();
    timer0_init();
    while (1)
    {
        if (BTN_RAND == 0)
        {
            while (BTN_RAND == 0)
            {
            }

            printf("RAND=%u\n", timer_rand());
        }

        if (BTN_SEED == 0)
        {
            while (BTN_SEED == 0)
            {
            }

            printf("SEED=%u\n", update_timer_seed());
        }
        if (BTN_TH_TL == 0)
        {
            while (BTN_TH_TL == 0)
            {
            }
            printf("THTL=0x%04X\n", (unsigned int)(TH0 << 8) | TL0);
        }
    }
}
